#include "StringOps.h"
#include <ctype.h>
#include <stdlib.h>
#include <sstream>
#include <stdio.h>
#include <algorithm>

std::vector<std::string> split(std::string _str, char _splitter) {
	std::vector<std::string> result;
	unsigned int i = 0;
	unsigned int last = 0;
	while(i < _str.length()) {
		if(_str[i] == _splitter) {
			result.push_back(_str.substr(last, i-last));
			last = i+1;
		}
		i++;
	}
	result.push_back(_str.substr(last, i-last));
	return result;
}

bool is_numeric(std::string _str) {
	char * p;
	strtod (_str.c_str(), &p);
	return *p == '\0';
}

using namespace std;

struct URL generate_url(std::string _url) {
	struct URL result;
	std::string url = _url;
	// Trim the protocol tag
	if(url.substr(0, 7) == "http://") {
		url = url.substr(7, url.size()-7);
	}

	// parse out the hostname and path
	int slashpos = url.find_first_of('/');
	if(slashpos != -1){
		result.host_name = url.substr(0, slashpos);
		result.path = url.substr(slashpos, url.size()-slashpos);
	}else{
		result.host_name = url;
		result.path = "";
	}
	
	return result;
}

int min(int x, int y) {
	return (x < y)?x:y;
}

string get_tag(string response, string tag) {
	string val;
	int pos = response.find(tag, 0);
	if(pos == -1)
		return "";
	int pos2 = min(response.find('\n',pos),response.find('\r',pos));
	string s = "\r\n";
	pos2 = min(pos2,response.find(s,pos));
	return response.substr(pos+tag.size(), pos2-pos-tag.size());
}

std::string get_error_code(std::string HTTP_Response) {
	// Skip the protocol
	int begin = HTTP_Response.find_first_of(' ');
	// Find space after error code
	int end = HTTP_Response.find_first_of(' ', begin+1);
	std::string code = HTTP_Response.substr(begin+1, end-begin-1);
	return code;
}

std::string get_error_description(std::string HTTP_Response) {
	std::stringstream ss(HTTP_Response);
	std::string desc;
	// Skip the protocol
	ss >> desc;
	// Skip the error code
	ss >> desc;
	// Here is the description
	ss >> desc;
	return desc;
}

std::string get_date(std::string HTTP_Response) {
	return get_tag(HTTP_Response, "Date: ");
}

std::string get_expires(std::string HTTP_Response) {
	return get_tag(HTTP_Response, "Expires: ");
}

std::string get_body(std::string HTTP_Response) {
	// Skip all tags
	int pos = 0;

	string end;
	end.push_back(10);
	end.push_back(10);
	pos = HTTP_Response.find(end, 0);
	string body = HTTP_Response.substr(pos+1, HTTP_Response.size()-pos-1);
	return body;
}
